<template>
  <div>
    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body :before-close="closeDelDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" clearable style="width: 90%" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年度" prop="year">
              <el-date-picker v-model="form.year" type="year" placeholder="选择年" clearable style="width: 90%" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="showDelete">
            <el-form-item label="单位" prop="registeredUnit">
              <el-input v-model="form.registeredUnit" placeholder="请输入单位" clearable style="width: 90%" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="退回原因" prop="returnReason">
              <el-input v-model="form.returnReason" type="textarea" placeholder="请输入内容" style="width: 90%" :rows="3" :disabled="!showDelete"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="书面材料">
              <div>
              <div  style="display: flex; flex-wrap: wrap; /* 允许子元素换行 */">
                <el-button class="upload_btn" type="primary" icon="el-icon-upload"
                    v-if="fileMJ == undefined && isFbState" @click="uploadTap">上传文件</el-button>
                <el-upload v-else class="upload-file-demo" action="上传的url" ref="writtenUpload" :auto-upload="true" :show-file-list='false' :limit="1"
                           v-show="showDelete" :accept="accept" :http-request="writtenFile" :file-list="writtenFileList">
                  <div style="width: 100%; display: flex">
                    <el-button type="primary" icon="el-icon-upload">上传文件</el-button>
                  </div>
                </el-upload>
                <el-select v-if="isFbState" style="margin-left:10px;" v-model="fileMJ" placeholder="请选择文件密级">
                    <el-option v-for="(item, idx) in renyuanOptions" :key="idx" :label="item.dictLabel"
                      :value="item.dictValue"></el-option>
                  </el-select>
              </div>
              
                <div v-for="item in writtenFileList" style="display: flex; margin-left: 1%" :key="item">
                  <span style="padding: 0 5px">{{ item.originalFile }}</span>
                  <p v-if="isFbState" style="border-bottom: 1px solid red;">
                      <span v-for="(i, idx) in renyuanOptions" :key="idx">
                        {{ item.mj == i.dictValue ? i.dictLabel : '' }}
                      </span>
                    </p>
                  <el-button type="text" @click="onPreviewTap(item)">预览</el-button>
                  <el-button type="text" v-show="showDelete" style="color: #ff0000" @click="deleteTap(item)">删除</el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="整改截止时间" prop="deadline">
              <el-date-picker v-model="form.deadline" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd" clearable style="width: 90%" :disabled="!showDelete"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-show="showDelete">
        <el-button type="primary" @click="returnForm">退 回</el-button>
        <el-button @click="resetlogin">重 置</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="45%" append-to-body>
      <div>
        <!--
         文件预览
         1、修改添加文件预览istype="1"
         2、查看组件详情istype="2"
         -->
        <FilePreview v-if="item" :item="item" :istype="istype" :moudle="1"></FilePreview>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {deleteFile, uploadFile} from "@/api/archive/supervision/annualInspectionNotice";
import FilePreview from "@/views/archive/supervision/supervises/filePreview";
import {updateById} from "@/api/archive/supervision/materialReporting";
import { getDicts_archive } from '@/api/archive/dict/dictManageData'
import { fbstat } from "@/api/archive/fileCollection/offlinReception.js";
import {
  getdamjbyrymj
} from "@/api/archive/fileCollection/offlinReception.js";
export default {
  name: "return",
  props: ['title', 'open', 'showDelete', 'dataInfo'],
  components: { FilePreview },
  data() {
    return {
      form: {
        title: undefined,
        year: undefined,
        returnReason: undefined,
        attachmentsList: [],
        deadline: undefined,
       
      },
      rules: {
        returnReason: [
          { required: true, message: "退回原因不能为空", trigger: "blur" },
        ],
        deadline: [
          { required: true, message: "整改截止时间不能为空", trigger: "blur" },
        ]
      },
      writtenFileList: [],
      accept: '.doc, .docx, .xls, .xlsx, .txt, .pdf, .gif, .jpeg, .png',
      viewOpen: false,
      viewTitle: '',
      item: '',
      istype: '1',
      renyuanOptions: [],//密级下拉列表
        isFbState: false,
        fileMJ: undefined,
    }
  },
  watch: {
    dataInfo: {
      handler(val) {
        this.form = JSON.parse(JSON.stringify(val));
        this.form.attachmentsList = val.attachmentsList.map(item => {
          // 为每个对象添加 docType 属性，并赋值为 originalFile后缀
          item.docType = this.getType(item.originalFile)
          return item;
        });
        this.writtenFileList = this.form.attachmentsList.filter(item=>item.fileType=='9')
      },
      deep: true
    }
  },
  created(){
    fbstat().then(res => {  //false=不是分保，true=是分保 
      this.isFbState = res.data
      if (this.isFbState) {
        //密级下拉列表
        getDicts_archive("MJ").then(res => { //人员密级
          getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
            var mjdata = [];
            for (var i in resdata.data) {
              for (var j in res.data) {
                if (resdata.data[i].daMj == res.data[j].dictValue) {
                  mjdata.push(res.data[j])
                }
              }
            }

            this.renyuanOptions = mjdata
          })
        })
      }
    })
  },
  methods: {
    uploadTap() {
      if (this.fileMJ == undefined) {
        this.$message.warning(`请选择密级`);
        return false
      }
    },
    closeDelDialog() {
      this.$emit('closeDelDialog')
    },
    returnForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.attachmentsList = this.form.attachmentsList.filter(item=> item.fileType!='9')
          if (this.writtenFileList.length != 0) {
            this.form.attachmentsList.push(...this.writtenFileList)
          }
          // 设置状态为4
          this.form.state = '3'
          updateById(this.form).then(res=>{
            this.$modal.msgSuccess('提交成功')
            this.closeDelDialog()
          }).catch(()=>{
            this.closeDelDialog()
          })
        }
      })
    },
    // 重置按钮
    resetlogin() {
      this.reset();
    },
    reset() {
      this.form.returnReason = undefined
      this.form.deadline = undefined
      this.form.attachmentsList = this.form.attachmentsList.filter(item=>item.fileType!='9')
    },
    // 获取文件类型
    getType(fileName) {
      let arr = fileName.split('.');
      let result = arr.pop();
      return result;
    },
    // 书面材料
    writtenFile(content) {
      this.file = content.file
      const formData = new FormData();
      formData.append("file", content.file);
      formData.append("type", '9');
      formData.append("id", this.form.id);
      if(this.fileMJ){
        formData.append("mj", this.fileMJ);
      }
      uploadFile(formData).then(response=>{
        this.writtenFileList.push({
          filePath: response.data.filePath,
          id: response.data.id,
          fileName: response.data.fileName,
          fileType: response.data.fileType,
          originalFile: response.data.originalFile,
          docType: this.getType(response.data.originalFile),
          mj: response.data.mj
        })
      })
    },
    // 预览
    onPreviewTap(item) {
      if (item.docType == 'OFD' || item.docType == 'ofd') {
        this.$modal.msgWarning('OFD文件不支持预览')
      } else {
        this.viewTitle = item.originalFile
        this.viewOpen = true
        this.item = item
      }
    },
    // 删除
    deleteTap(item) {
      var form = {
        noticesId: this.dataInfo.id,
        attachmentsId: item.id,
        attachmentsType: item.fileType
      }
      this.$modal.confirm('是否确认删除名为"' + item.originalFile + '"的附件？').then(function() {
        return deleteFile(form)
      }).then(res => {
        this.getFileList(form)
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {});
    },
    getFileList(form) {
      if (form.attachmentsType == '9') {
        this.writtenFileList = this.writtenFileList.filter(item => item.id !== form.attachmentsId);
      }
    }
  }
}
</script>

<style scoped>

</style>
